package com.ruoyi.lxy.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StreamUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.lxy.domain.TProjectTravelagen;
import com.ruoyi.lxy.mapper.TProjectTravelagenMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.lxy.domain.bo.TTravelagenBo;
import com.ruoyi.lxy.domain.vo.TTravelagenVo;
import com.ruoyi.lxy.domain.TTravelagen;
import com.ruoyi.lxy.mapper.TTravelagenMapper;
import com.ruoyi.lxy.service.ITTravelagenService;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 旅行社Service业务层处理
 *
 * @author ruoyi
 * @date 2023-08-25
 */
@RequiredArgsConstructor
@Service
public class TTravelagenServiceImpl implements ITTravelagenService {

    private final TTravelagenMapper baseMapper;
    private final TProjectTravelagenMapper projectTravelagenMapper;

    @Override
    public SysUser transfer(TTravelagenBo bo) {
        SysUser user=new SysUser();
        user.setUserId(bo.getId());
        user.setUserName(bo.getUsername());
        user.setNickName(bo.getAgencyName());
        user.setEmail(bo.getPrincipalEmail());
        user.setPhonenumber(bo.getPrincipalPhone());
        user.setPassword(BCrypt.hashpw(bo.getPassword()));

        user.setUserType("sys_user");
        user.setRoleIds(new Long[]{2L});//设置为旅行社
        if(bo.getStatus()!=null){
            user.setStatus(bo.getStatus().toString());
        }
        if(StringUtils.isNotEmpty(user.getPhonenumber()))
            user.setRemark("负责人："+bo.getPrincipalName());
        return user;
    }

    /**
     * 查询旅行社
     */
    @Override
    public TTravelagenVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询旅行社列表
     */
    @Override
    public TableDataInfo<TTravelagenVo> queryPageList(TTravelagenBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TTravelagen> lqw = buildQueryWrapper(bo);
        Page<TTravelagenVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询旅行社列表
     */
    @Override
    public List<TTravelagenVo> queryList(TTravelagenBo bo) {
        LambdaQueryWrapper<TTravelagen> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TTravelagen> buildQueryWrapper(TTravelagenBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TTravelagen> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getUsername()), TTravelagen::getUsername, bo.getUsername());
        lqw.like(StringUtils.isNotBlank(bo.getPassword()), TTravelagen::getPassword, bo.getPassword());
        lqw.like(StringUtils.isNotBlank(bo.getAgencyName()), TTravelagen::getAgencyName, bo.getAgencyName());
        lqw.like(StringUtils.isNotBlank(bo.getPrincipalName()), TTravelagen::getPrincipalName, bo.getPrincipalName());
        lqw.like(StringUtils.isNotBlank(bo.getPrincipalPhone()), TTravelagen::getPrincipalPhone, bo.getPrincipalPhone());
        lqw.like(StringUtils.isNotBlank(bo.getPrincipalEmail()), TTravelagen::getPrincipalEmail, bo.getPrincipalEmail());
        lqw.eq(bo.getStatus() != null, TTravelagen::getStatus, bo.getStatus());
        if(bo.getProjectIds()!=null){
            List<Long> ids=projectTravelagenMapper.selectList(new LambdaQueryWrapper<TProjectTravelagen>()
                    .select(TProjectTravelagen::getTravelagenId)
                    .in(TProjectTravelagen::getProjectId, bo.getProjectIds()))
                .stream()
                .map(TProjectTravelagen::getTravelagenId)
                .collect(Collectors.toList());
            lqw.in(TTravelagen::getId,ids);
        }
        return lqw;
    }

    /**
     * 新增旅行社
     */
    @Override
    public Boolean insertByBo(TTravelagenBo bo) {
        //新增旅行社信息
        TTravelagen add = BeanUtil.toBean(bo, TTravelagen.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        //新增旅行社 项目关联
        insertAgencyProject(bo.getId(), bo.getProjectIds());
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }
    /**
     * 新增旅行社 项目关联
     */
    public void insertAgencyProject(Long agencyId,Long[] projects) {
        if(ArrayUtil.isNotEmpty(projects)){
            //旅行社 项目关联
            List<TProjectTravelagen> list= StreamUtils.toList(Arrays.asList(projects),projectId->{
                TProjectTravelagen pt=new TProjectTravelagen();
                pt.setProjectId(projectId);
                pt.setTravelagenId(agencyId);
                return pt;
            });
            projectTravelagenMapper.insertBatch(list);
        }
    }

    /**
     * 修改旅行社 项目关联
     */
    public void updateAgencyProject(Long agencyId,Long[] projects){
        // 删除旅行社与项目关联
        projectTravelagenMapper.delete(new LambdaQueryWrapper<TProjectTravelagen>().eq(TProjectTravelagen::getTravelagenId, agencyId));
        // 新增旅行社与项目关联
        insertAgencyProject(agencyId,projects);
    }


    /**
     * 修改旅行社
     */
    @Override
    public Boolean updateByBo(TTravelagenBo bo) {
        Long agencyId = bo.getId();
        //修改 旅行社与项目 关联
        updateAgencyProject(agencyId,bo.getProjectIds());
        TTravelagen update = BeanUtil.toBean(bo, TTravelagen.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 修改旅行社状态
     */
    @Override
    public Boolean updateUserStatus(TTravelagenBo bo) {
        TTravelagen update = BeanUtil.toBean(bo, TTravelagen.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }
    /**
     * 重置用户密码
     */
    @Override
    public int resetPwd(TTravelagenBo bo) {
        TTravelagen update = BeanUtil.toBean(bo, TTravelagen.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TTravelagen entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除旅行社
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
